package com.wuxianedu.contentproviderdemo;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.util.Log;

import com.wuxianedu.contentproviderdemo.db.MyOpenHelper;

/**
 * Created by TED on 2016/9/20.
 */
public class MyProvider extends ContentProvider {

    private SQLiteDatabase db;


    private static final int ANDROID_CODE = 1;

    private static final int USER_CODE = 2;

    private static final int USER_CODE_ONCE = 3;// 查询一条数据

    // 这里是固定写法
    static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    static {
        //添加uri的匹配规则
        uriMatcher.addURI("com.hangzhou.gujia.android94", "android", ANDROID_CODE);
        uriMatcher.addURI("com.hangzhou.gujia.android94", "user", USER_CODE);
        uriMatcher.addURI("com.hangzhou.gujia.android94", "user/#", USER_CODE_ONCE);

    }

    @Override
    public boolean onCreate() {
        MyOpenHelper myOpenHelper = new MyOpenHelper(getContext());
        db = myOpenHelper.getReadableDatabase();
        return false;
    }


    //content://com.hangzhou.gujia.android94/user/3
    //content://com.hangzhou.gujia.android94/user
    @Nullable
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        Cursor cursor = null;
        switch (uriMatcher.match(uri)) {
            case ANDROID_CODE:
                Log.i("--------", "----query---android--");
                break;
            case USER_CODE:
                Log.i("--------", "----query---user--");
                break;
            case USER_CODE_ONCE:
                long id = ContentUris.parseId(uri);
                cursor = db.query("user",null,"_id = ?",new String[]{id+""},null,null,null);
                Log.i("--------", "----query---user-#--");
                break;
        }
        return cursor;
    }

    @Nullable
    @Override
    public String getType(Uri uri) {
        return null;
    }



    @Nullable
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        switch (uriMatcher.match(uri)) {
            case ANDROID_CODE:

                Log.i("--------", "----insert---android--");
                break;
            case USER_CODE:
                db.insert("user", null, values);
                Log.i("--------", "----insert---user--");
                break;
            case UriMatcher.NO_MATCH:
                throw new RuntimeException("床上是你的，床下的是我的，滚。。。");
        }




        return null;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        return 0;
    }
}
